<template>
    <n-form
        ref="formRef"
        label-placement="top"
        :label-width="80"
        :model="form"
        :rules="rules"
    >
        <n-form-item label="岗位名称" path="name">
            <n-input v-model:value="form.name" placeholder="请输入岗位名称" />
        </n-form-item>
        <n-form-item label="岗位类型" path="type">
            <jb-select
                v-model:value="form.type"
                url="/api/admin/dictionary/options?typeKey=post_type"
                placeholder="=请选择="
                :clearable="false"
                filterable
                class="w-140px"
            ></jb-select>
        </n-form-item>
        <n-form-item label="编码" path="sn">
            <n-input v-model:value="form.sn" placeholder="请输入编码" />
        </n-form-item>
        <n-form-item label="备注信息">
            <n-input
                v-model:value="form.remark"
                type="textarea"
                placeholder="请输入备注信息"
            />
        </n-form-item>
    </n-form>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { FormInst, FormRules } from 'naive-ui'
import { Rules } from '@/utils'
import { JBoltApi } from '@/utils/request'
import { useResetableData } from '@/hooks/common/use-resetable-data'
import { ResData } from '@/typings/request'

const props = withDefaults(
    defineProps<{
        id: string
    }>(),
    {
        id: ''
    }
)

/** 表单相关 start */
const formRef = ref<FormInst | null>()
interface PostType {
    id: string
    name: string
    type: number
    sn: string
    remark: string
}
const form = useResetableData<PostType>({
    id: '',
    name: '',
    type: 0,
    sn: '',
    remark: ''
})
const rules: FormRules = {
    name: new Rules().required('请输入名称').value,
    type: new Rules().required('请选择类型').value,
    sn: new Rules().required('请输入编码').value
}

/**
 * 提交表单
 */
async function submit() {
    await formRef.value?.validate()

    let url = props.id ? '/api/admin/post/update' : '/api/admin/post/save'
    await JBoltApi.tryPost(url, form)
    await window.$success('保存成功')
    return true
}

function loadEditData() {
    JBoltApi.get<ResData>(`/api/admin/post/${props.id}`).then(({ error, result }) => {
        if (error) return
        form._reset(result.data)
    })
}

onMounted(() => {
    if (props.id) {
        loadEditData()
    }
})

defineExpose({
    submit
})

/** 表单相关 end */
</script>
<style scoped></style>
